package com.yc.hanlder;

import com.yc.CustomException;
import com.yc.R_Code;
import com.yc.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 统一参数异常拦截器
 * @author LC
 */
@RestControllerAdvice
@Slf4j
public class ExceptionHandle {

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result exceptionHandler(MethodArgumentNotValidException e) {
        log.error(Result.error().code(R_Code.R_PARAM_FAIL.getCode()).message(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage()).buildString());
        return Result.error().code(R_Code.R_PARAM_FAIL.getCode()).message(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        log.error(Result.error().buildString());
        e.printStackTrace();
        return Result.error().message(e.toString());
    }

    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public Result exceptionHandler(CustomException e) {
        log.error(Result.error().buildString());
        return Result.error().code(e.getCode()).message(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(AuthenticationException.class)
    public Result handleAuthorizationException(HttpServletRequest request, AuthenticationException e) {
        log.error(e.getMessage(), e);
        return Result.error().message(e.toString());
    }

}
